package com.zjpavt.client.util;

import org.apache.commons.io.IOUtils;
import purejavacomm.*;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.TooManyListenersException;


/**
 * 串口服务类，提供打开、关闭串口，读取、发送串口数据
 */
public class PortUtil {

    /**
     * 查找所有可用端口
     *
     * @return 可用端口名称列表
     */
    public static ArrayList<String> findPort() {
        // 获得当前所有可用串口
        Enumeration<CommPortIdentifier> portList = CommPortIdentifier
                .getPortIdentifiers();
        ArrayList<String> portNameList = new ArrayList<>();
        // 将可用串口名添加到List并返回该List
        while (portList.hasMoreElements()) {
            String portName = portList.nextElement().getName();
            portNameList.add(portName);
        }
        return portNameList;
    }

    /**
     * 打开串口
     *
     * @param portName 端口名称
     * @return 串口对象
     */
    public static SerialPort openPortWithDefaultBaudrate(String portName) throws Exception {
        return openPort(portName, 9600);
    }

    /**
     * 打开串口
     *
     * @param portName 端口名称
     * @param baudrate 波特率
     * @return 串口对象
     */
    public static SerialPort openPort(String portName, int baudrate)
    throws Exception {
        try {
            // 通过端口名识别端口
            CommPortIdentifier portIdentifier = CommPortIdentifier
            .getPortIdentifier(portName);
            // 打开端口，并给端口名字和一个timeout（打开操作的超时时间）
            CommPort commPort = portIdentifier.open(portName, 2000);
            // 判断是不是串口
            if (commPort instanceof SerialPort) {
                SerialPort serialPort = (SerialPort) commPort;
                try {
                    // 设置串口的波特率等参数
                    serialPort.setSerialPortParams(baudrate,
                                                   SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
                                                   SerialPort.PARITY_NONE);
                } catch (UnsupportedCommOperationException e) {
                    throw new Exception("FAIL TO SET PORT PARAMS");
                }
                return serialPort;
            } else {
                // 不是串口
                throw new Exception("ITS NOT A PORT");
            }
        } catch (NoSuchPortException e1) {
            throw new Exception("NO SUCH PORT FOUND");
        } catch (PortInUseException e2) {
            throw new Exception("PORT ALREADY IN USE");
        }
    }

    /**
     * 关闭串口
     *
     * @param serialPort 待关闭的串口对象
     */
    public static void closePort(SerialPort serialPort) {
        if (serialPort != null) {
            serialPort.close();
            serialPort = null;
        }
    }

    /**
     * 往串口发送数据
     *
     * @param serialPort 串口对象
     * @param order      待发送数据
     */
    public static void sendToPort(SerialPort serialPort, byte[] order)
    throws Exception {
        OutputStream out = null;
        try {
            out = serialPort.getOutputStream();
            out.write(order);
            out.flush();
        } catch (IOException e) {
            throw new Exception("FAIL TO SEND TO PORT");
        }
        finally {
            IOUtils.closeQuietly(out);
        }
    }

    /**
     * 往串口发送数据
     *
     * @param serialPort 串口对象
     * @param data       待发送数据
     */
    public static void sendToPort(SerialPort serialPort, String data)
    throws Exception {
        if (data == null || data.isEmpty()) {
            return;
        }
        sendToPort(serialPort, data.getBytes(ClientConfig.DEFAULT_ENCODING));
    }

    /**
     * 从串口读取数据
     *
     * @param serialPort 当前已建立连接的SerialPort对象
     * @return 读取到的数据
     */
    public static byte[] readFromPort(SerialPort serialPort) throws Exception {
        InputStream in = null;
        byte[] bytes = {};
        try {
            in = serialPort.getInputStream();
            // 缓冲区大小为一个字节
            byte[] readBuffer = new byte[1];
            int bytesNum = in.read(readBuffer);
            while (bytesNum > 0) {
                if (bytes == null) {
                    return null;
                }
                bytes = new byte[bytes.length + readBuffer.length];
                System.arraycopy(bytes, 0, bytes, 0, bytes.length);
                System.arraycopy(readBuffer, 0, bytes, bytes.length,
                                 readBuffer.length);
                bytesNum = in.read(readBuffer);
            }
        } catch (IOException e) {
            throw new Exception("FAIL TO READ FROM PORT");
        }
        finally {
            IOUtils.closeQuietly(in);
        }
        return bytes;
    }

    /**
     * 从串口读取数据
     *
     * @param serialPort 当前已建立连接的SerialPort对象
     * @return 读取到的数据
     */
    public static String readStringFromPort(SerialPort serialPort) throws Exception {
        byte[] bytes = readFromPort(serialPort);
        if (bytes == null) {
            return "";
        }
        return new String(bytes, ClientConfig.DEFAULT_ENCODING);
    }

    /**
     * 添加监听器
     *
     * @param port     串口对象
     * @param listener 串口监听器
     * @throws Exception 监听类对象过多
     */
    public static void addPortListener(SerialPort port,
                                       SerialPortEventListener listener) throws Exception {
        try {
            // 给串口添加监听器
            port.addEventListener(listener);
            // 设置当有数据到达时唤醒监听接收线程
            port.notifyOnDataAvailable(true);
            // 设置当通信中断时唤醒中断线程
            port.notifyOnBreakInterrupt(true);
        } catch (TooManyListenersException e) {
            throw new Exception("TOO MANY LISTENERS,FAIL TO BIND");
        }
    }

    /**
     * 移除监听器
     *
     * @param port 串口对象
     */
    public static void removePortListener(SerialPort port) {
        port.removeEventListener();
    }

}
